package com.thinkverse.user.controller;

import com.thinkverse.user.dto.ApiResponse;
import com.thinkverse.user.dto.ChangePasswordRequestDTO;
import com.thinkverse.user.dto.UpdateUserRequestDTO;
import com.thinkverse.user.entity.User;
import com.thinkverse.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户信息控制器
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "用户信息相关接口")
@RequiredArgsConstructor
public class UserController {

    @Autowired
    private UserService userService;

    private Long resolveUserId(HttpServletRequest req) {
        String idStr = req.getHeader("X-USER-ID");
        if (idStr == null || idStr.isBlank()) {
            // 尝试 X-USERNAME 再失败
            throw new RuntimeException("请先登录");
        }
        try {
            return Long.valueOf(idStr);
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的用户ID");
        }
    }

    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息")
    public ApiResponse<User> getCurrentUser(HttpServletRequest req) {
        Long userId = resolveUserId(req);
        User u = userService.getCurrentUser(userId);
        return ApiResponse.success(u);
    }

    @PutMapping("/me")
    @Operation(summary = "更新个人信息")
    public ApiResponse<String> updateUserInfo(HttpServletRequest req, @Valid @RequestBody UpdateUserRequestDTO request) {
        Long userId = resolveUserId(req);
        userService.updateUserInfo(userId, request);
        return ApiResponse.success("更新成功");
    }

    @PutMapping("/password")
    @Operation(summary = "修改密码")
    public ApiResponse<String> changePassword(HttpServletRequest req, @Valid @RequestBody ChangePasswordRequestDTO request) {
        Long userId = resolveUserId(req);
        userService.changePassword(userId, request);
        return ApiResponse.success("密码修改成功");
    }
}
